package edu.scau.web.payment;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.scau.core.constants.AjaxResult;
import edu.scau.payment.config.AliPayConfig;
import edu.scau.payment.service.PaymentService;
import edu.scau.pos.service.SaleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;
@Tag(name = "页面接口,废弃")
@Controller
@RequestMapping("page")
public class PayIndexController {
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private SaleService saleService;

    /**
     * 返回页面的支付调用测试接口
     * @param model
     * @return
     * @throws AlipayApiException
     */
    @GetMapping("/pay")
    public String pay(Model model) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(paymentService.getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount = "1.1";
        //订单名称，必填
        String subject = "名称";
        //商品描述，可空
        String body = "boy";
        String timeout = "1m";


        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+timeout+"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String returnUrl = "http://10.144.165.46:8081/page/query?" ; // 支付成功后跳转到 query 接口
//        String notifyUrl = "https://yourdomain.com/payment/notify"; // 接收支付宝异步通知的接口

        request.setReturnUrl(returnUrl);
//        request.setNotifyUrl(notifyUrl);

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        model.addAttribute("form", pageRedirectionData);

        if (response.isSuccess()) {
            System.out.println("调用成功");
            return "pay";
        } else {
            System.out.println("调用失败");
            return "";
        }
    }

    /**
     * 回调查询交易成功订单的状态  paymentService
     * @param params 回调查询参数
     * @return page
     * @throws AlipayApiException
     */
    @GetMapping("/query")
    public String query(@RequestParam Map<String, String> params,Model model) throws AlipayApiException, JsonProcessingException {
        //不验签了
        String outTradeNo = params.get("out_trade_no");

        // 3. 查询订单状态
        AlipayClient alipayClient = new DefaultAlipayClient(paymentService.getAlipayConfig());
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel dateModel = new AlipayTradeQueryModel();
        dateModel.setOutTradeNo(outTradeNo);
        List<String> queryOptions = new ArrayList<>();
        queryOptions.add("trade_settle_info");
        dateModel.setQueryOptions(queryOptions);
        request.setBizModel(dateModel);
        //查询订单状态
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        //解析
        Map<String,Object> resultMap=this.paseMap(response);
        if (response.isSuccess()) {
            if(Objects.equals((String) resultMap.get("trade_status"), "TRADE_SUCCESS")){
                //执行回调入库

                model.addAttribute("transactionId", resultMap.get("trade_no"));
                model.addAttribute("transactionTime", resultMap.get("send_pay_date"));
                model.addAttribute("transactionAmount", resultMap.get("total_amount"));
                return "success";
            }
            else {
                return "error";
            }
        }
        else {
            return "error";
        }
    }
    public Map<String, Object>  paseMap(AlipayTradeQueryResponse response) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> responseMap = mapper.readValue(response.getBody(), Map.class);

        Map<String, Object> tradeQueryResponse = (Map<String, Object>) responseMap.get("alipay_trade_query_response");

        return tradeQueryResponse;
    }

}
